//201902104003邵潇漩
package bysj.service;

import bysj.dao.UserDao;
import bysj.domain.User;
import bysj.domain.authority.Actor;
import bysj.domain.authority.ActorAssRole;
import bysj.domain.authority.Resource;
import bysj.domain.authority.Role;
import com.alibaba.fastjson.JSONObject;
import util.JdbcHelper;
import util.TokenHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeSet;

public final class UserService {
	private UserDao userDao = UserDao.getInstance();
	private static UserService userService = new UserService();
	
	public UserService() {
	}
	
	public static UserService getInstance(){
		return UserService.userService;
	}


	public Collection<User> getUsers()throws SQLException{
		return userDao.findAll();
	}
	
//	public User getUser(Integer id)throws SQLException {
//		return userDao.find(id);
//	}
	
	/*public boolean updateUser(User user){
		return userDao.update(user);
	}
	
	public boolean addUser(User user){
		return userDao.add(user);
	}

	public boolean deleteUser(Integer id)throws SQLException{
		User user = this.getUser(id);
		return this.deleteUser(user);
	}
	
	public boolean deleteUser(User user){
		return userDao.delete(user);
	}*/
	public Actor login(User userToLogin,JSONObject message) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		Actor actor = userDao.login(connection, userToLogin);
		if (actor == null) {
			return null;
		} else {
			Collection<ActorAssRole> actorAssRoleCollection = ActorAssRoleService.getInstance().findAll(actor);
			Collection<Role> roles = new TreeSet<>();
			for (ActorAssRole actorAssRole : actorAssRoleCollection) {
				Role role = actorAssRole.getRole();
				roles.add(role);
			}
			userToLogin.setRoles(roles);
			HashMap<Integer, String> map = new HashMap<>();
			int urlID = 1;
			Collection<Role> roles1 = userToLogin.getRoles();
			for (Role role : roles1) {
				Collection<Resource> resources = role.getResources();
				for (Resource resource : resources) {
					String url = resource.getUrl();
					map.put(urlID, url);
				}
			}
			message.put("roles", roles);
			String token = TokenHelper.getToken(map);
			message.put("token",token);
		}
		JdbcHelper.close(connection);
		return actor;
	}
}
